package com.ubing.gpermission.permission.aop;

import com.ubing.gpermission.permission.annotation.Permission;
import com.ubing.gpermission.permission.annotation.PermissionRouter;
import com.ubing.gpermission.permission.exception.NoPermissionException;
import com.ubing.gpermission.permission.handler.PermissionHandler;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;


/**
 * 用户权限切面切面注解
 *
 * @author ubing
 * @version 1.0.0
 * @date 2023-12-05 11:11
 */
@Aspect
public class PermissionAop {

	@Pointcut("@annotation(com.ubing.gpermission.permission.annotation.Permission)")
	public void PermissionAopPointcut() {}

	@Resource
	private PermissionHandler permissionHandler;

	@Around("PermissionAopPointcut()")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		PermissionRouter router = (PermissionRouter)signature.getDeclaringType().getAnnotation(PermissionRouter.class);
		String routerValue = router.value();
		Method method = signature.getMethod();
		Permission permission = method.getAnnotation(Permission.class);
		String permissionValue = permission.value();
		if (!permissionHandler.beforePermissionHandle(routerValue,permissionValue)||!permissionHandler.afterPermissionHandle(routerValue,permissionValue)) {
			throw new NoPermissionException("没有接口权限："+permissionValue);
		}
		return joinPoint.proceed();
	}
}
